import axios from 'axios';
import qs from 'qs';
import { Toast } from 'vant';
import store from '../../store/index';
import router from '../../router';

let toastFn = function(msg, duration){
    Toast({
        message: msg,
        duration: duration || 1500,
        forbidClick: true
    });
}

//线上地址
// const baseURL = 'http://wx.umubao.com/';
//测试地址 
const baseURL = 'http://cs.umubao.com/ymfarm-1.0-SNAPSHOT';
//const baseURL = 'http://172.16.117.212:8080/api';
// const baseURL = 'http://10.10.0.106:8080'   //  海波地址
//本地地址 
// const baseURL = 'http://192.168.0.18:8080'; //永耀
// const baseURL = 'http://10.10.0.106:8080'; //海波


axios.defaults.baseURL = baseURL;

//是否打印请求返回值(打包上线时设为false)
// const showResponse = true;
const showResponse = false;

// 请求超时时间
axios.defaults.timeout = 5000;

// 跨域请求时是否需要使用凭证
axios.defaults.withCredentials = true;
// axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';  //证明是ajax 请求

// 添加请求拦截器
axios.interceptors.request.use(config => {
    if(!config.url.includes('noLoading')){
        Toast.loading({
            mask: true,
            message: '请求中...'
        });
    }
    
    // 请求token
    if (store.getters.token) {
        // config.headers.Authorization = 'store.getters.token';
        config.headers.Authorization = store.getters.token;
    }
    
    if (Array.isArray(config.data)) {
        axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
    } else {
        axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
        if (config.method === 'post') {
            config.data = qs.stringify(config.data);
        }
    }
    return config;
}, error => {
    console.log(error);
    Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(
    response => {
        Toast.clear();
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {            
            return Promise.reject(response);        
        }
    }, error => {
        Toast.clear();
        console.log("responseerr:" + error);
        toastFn('网络请求错误，请稍后重试')
        return Promise.reject(error.response);
    });

const httpSuccessFn = function(resolve, res){ //请求成功处理
    switch(res.data.code) {
        case 0:
            resolve(res.data);
            break;
        case 10000:
            toastFn(res.data.message, 1000)
            setTimeout(() => {
                router.replace({
                    path: '/login'
                })
            }, 1000)
            break;
        case 10011:
            resolve(res.data);
            break;
        case 20014:    //交易密码错误
			resolve(res);
			break;
		case 60005:   //检验是否是自己挂的单
			resolve(res);
            break;
        case 90005:   //牛订单的物流信息
			resolve(res);
			break;
        default:
            toastFn(res.data.message);
            break;
    }
}

const http = {
    /**
     * get方法，对应get请求
     * @param {String} url [请求的url地址]
     * @param {Object} params [请求时携带的参数]
     */
    get(url, params){    
        return new Promise((resolve, reject) =>{        
            axios.get(url, {            
                params: params        
            })
            .then(res => {
                if(showResponse){
                    console.log(`get ${url}`, res.data)
                }
                httpSuccessFn(resolve, res)
            })
            .catch(err =>{
                console.log('geterr:',err)
                if(err.status == 404){
                    toastFn('请求的资源不存在')
                    return;
                }
                toastFn('请求错误，请稍后重试')
                // reject(err.data)
            })    
        });
    },

    /** 
     * post方法，对应post请求 
     * @param {String} url [请求的url地址] 
     * @param {Object} data [请求时携带的参数] 
     */
    post(url, data) {
        return new Promise((resolve, reject) => {
            axios.post(url, data)
            .then(res => {
                if(showResponse){
                    console.log(`post ${url}`, res.data)
                }
                httpSuccessFn(resolve, res)
            })
            .catch(err =>{
                console.log('posterr:',err)
                if(err.status == 404){
                    toastFn('请求的资源不存在')
                    return;
                }
                toastFn('请求错误，请稍后重试')
                // reject(err)
            })
        });
    }
}

export default http;